﻿using System;
using System.Collections.Generic;
using System.Linq;
using T.FAS.Runtime.Base.Common;
using T.FAS.Runtime.Metadata.Entity.DataModel;

namespace T.FAS.Runtime.DataAccess.SQLDom
{
    /// <summary>
    /// 权限执行控制上下文类
    /// </summary>
    public class AuthControlContext
    {
        /// <summary>
        /// 是否需要鉴权,false:不需要
        /// </summary>
        public bool IsNeedAuth { get; private set; }

        /// <summary>
        /// 列权限鉴权结果
        /// </summary>
        public List<ColumnPermissionView> ColumnPermissionResult { get; private set; }

        /// <summary>
        /// 初始化权限控制
        /// </summary>
        /// <param name="isNeedAuth"></param>
        /// <param name="columnPermissionResult"></param>
        public void InitAuthControl(bool isNeedAuth, List<ColumnPermissionView> columnPermissionResult)
        {
            //如果启用开关配置
            if (ConfigProvider.Instance.EnableGlobalMask == true)
            {
                IsNeedAuth = isNeedAuth;
            }
            else
            {
                IsNeedAuth = false;
            }
            ColumnPermissionResult = columnPermissionResult;
        }

        /// <summary>
        /// 判断是否有权限
        /// </summary>
        /// <param name="dataObject"></param>
        /// <param name="dataColumn"></param>
        /// <returns>true:有权限，false:无权限</returns>
        public bool IsHasPermission(DataObject dataObject, DataColumn dataColumn)
        {
            //如果不校验权限，返回true
            if (!IsNeedAuth) return true;
            if (dataObject == null || dataColumn == null)
            {
                throw new Exception($"valid column permission failed, dataObject & dataColumn cannot be null");
            }
            //如果列没有启用权限，返回true
            if (!dataColumn.IsEnableColumnPermission) return true;
            else
            {
                //如果启用掩码且未启用FAS存储的话，不校验权限，直接返回明文
                if (dataColumn.MaskingRule?.IsEnable == true && !ConfigUtil.Instance.EnableFASMaskStorage)
                {
                    return true;
                }
                else
                {
                    if (LiveDebug.IsDebug)
                    {
                        if (LiveDebug.IsAllAuth)
                            return true;
                        if (LiveDebug.IsNoAuth)
                            return false;
                    }
                    //如果鉴权结果为空，返回false
                    if (ColumnPermissionResult == null) return false;
                    //鉴权
                    return ColumnPermissionResult.Any(p => p.DoId == dataObject.ID && p.ID == dataColumn.ID);
                }
            }
        }
    }
}